package com.client.smartauction;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {

	final String SERVERIP = "192.168.168.101";
	final int SERVERPORT = 5000;
	final String TAG = "MainActivity";
	private ArrayList<Product> mProducts;
	private ListView mListView;
	private ProAdapter mAdapter;
	private ProListner mProListener;
	private ListAsynk asynk;
	private Intent intent;
	private String mId;
	private String mPassWord;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		intent = getIntent();
		mId = intent.getStringExtra("ID");
		mPassWord = intent.getStringExtra("PassWord");
		
		mProducts = new ArrayList<Product>();
		mProducts.add(new Product("[현대백화점]상품권(10만원권)", "5000",
				"2012-12-03 10:13:46 ", "현대백화점 상품권"));
		mProducts.add(new Product("안드로이드 도킹 스피커", "5000",
				"2012-12-03 15:53:10", "스피커"));
		mProducts.add(new Product("갤럭시 노트 10.1 Wifi(16GB)", "3000",
				"2012-12-03 16:21:33", "태블릿"));
		mProducts.add(new Product("최신형 게이트맨 S2 리모컨형", "4000",
				"2012-12-03 20:22:13", "락 도어 "));
		mAdapter = new ProAdapter(this, R.layout.listrow, mProducts);
		mProListener = new ProListner();
		setListAdapter(mAdapter);
		mListView = getListView();
		mListView.setOnItemClickListener(mProListener);
		asynk = new ListAsynk();
		asynk.execute();
	}

	@Override
	protected void onResume() {

		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	private class ListAsynk extends AsyncTask<Void, Void, String> {

		private Socket socket;
		private String line = null;
		ProgressDialog dialog;

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {

				socket = new Socket(SERVERIP, SERVERPORT);
				OutputStream outputStream = socket.getOutputStream();
				
				JSONObject jsonobj = new JSONObject();
				try {
					jsonobj.put("HEADER", "LIST");

					outputStream.write(jsonobj.toString().getBytes());
					outputStream.flush();

				} catch (JSONException e) {
					e.printStackTrace();
				}

				InputStream inputStream = socket.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] byteBuffer = new byte[1024];
				byte[] byteData = null;
				int nLength = 0;
				while ((nLength = inputStream.read(byteBuffer, 0,
						byteBuffer.length)) != -1) {
					baos.write(byteBuffer, 0, nLength);
				}
				byteData = baos.toByteArray();
				line = new String(byteData);

			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "unknownHost");
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return line;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			//dialog = ProgressDialog.show(MainActivity.this, "Downloading",
			//		"Please Wait.....", true, false);
			super.onPreExecute();
		}

		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result == null) {
				//dialog.setMessage("Fail to Download");
			}
			try {
				if (result != null) {

					// /////////////////////////////////////////////////////////////////////////
					JSONObject jsonobject = new JSONObject(result);
					try {
						String header = jsonobject.getString("HEADER");
						if (header.equals("CONNECTOK")) {
							String proName = jsonobject
									.getString("PRODUCT_NAME");
							String proInitprice = jsonobject
									.getString("PRODUCT_INIT_PRICE");
							String proTime = jsonobject
									.getString("PRODUCT_INIT_TIME");
							String proDes = jsonobject.getString("PRODUCT_DES");
							mProducts.add(new Product(proName, proInitprice,
									proTime, proDes));
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			mAdapter.setNotifyOnChange(true);
			mAdapter.notifyDataSetChanged();
			//dialog.dismiss();
			super.onPostExecute(result);

		}
	}

	private class ProListner implements OnItemClickListener {
		public void onItemClick(AdapterView<?> ParentView, View view,
				int position, long id) {

			if (asynk.isCancelled() == false) {
				Product p = mProducts.get(position);
				intent = new Intent(MainActivity.this, BiddingActivity.class);
				intent.putExtra("name", p.getName());
				intent.putExtra("price", p.getInitPrice());
				intent.putExtra("time", p.getStartTime());
				intent.putExtra("des", p.getDes());
				intent.putExtra("serverip", SERVERIP);
				intent.putExtra("ID", mId);
				intent.putExtra("PassWord", mPassWord);

				startActivity(intent);
			}
		}
	}

	private class ProAdapter extends ArrayAdapter<Product> {
		private Product p;
		private ArrayList<Product> items;

		public ProAdapter(Context context, int textViewResourceId,
				ArrayList<Product> _items) {
			super(context, textViewResourceId, _items);

			items = _items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.listrow, null);
			}
			p = items.get(position);
			if (p != null) {
				TextView nt = (TextView) v.findViewById(R.id.ProductName);
				TextView pt = (TextView) v.findViewById(R.id.Price);
				TextView st = (TextView) v.findViewById(R.id.Inittime);

				nt.setText(p.getName());
				pt.setText(p.getInitPrice() + "원");
				st.setText(p.getStartTime());
			}

			return v;

		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}
